package com.syn.synold4s.activity.surveillance;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import androidx.activity.OnBackPressedCallback;
import androidx.activity.result.ActivityResult;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.gaoyi.basemodule.baseCallback.IView;
import com.gaoyi.basemodule.baseUtil.AppUtil;
import com.gaoyi.basemodule.baseUtil.GsonUtil;
import com.gaoyi.basemodule.baseUtil.SPUtil;
import com.gaoyi.basemodule.baseUtil.SmartRefreshUtil;
import com.gaoyi.basemodule.baseUtil.WindowUtil;
import com.gaoyi.basemodule.baseact.BaseActivity;
import com.gaoyi.basemodule.basebean.Event;
import com.gaoyi.basemodule.basebean.LoginDto;
import com.gaoyi.basemodule.basebean.UserTagDto;
import com.gaoyi.basemodule.baseconstant.Constants;
import com.gaoyi.basemodule.baseconstant.SPName;
import com.gaoyi.basemodule.basedialog.LoadingDialogUtils;
import com.google.gson.reflect.TypeToken;
import com.syn.synold4s.R;
import com.syn.synold4s.activity.MainActivity;
import com.syn.synold4s.activity.google_map.GoogleMapActivity;
import com.syn.synold4s.activity.setting.SettingActivity;
import com.syn.synold4s.adapter.CctvRvAdapter;
import com.syn.synold4s.adapter.DrawerAdapter;
import com.syn.synold4s.constants.TagCode;
import com.syn.synold4s.databinding.ActivitySurveillanceBinding;
import com.syn.synold4s.util.MyAnimUtil;
import com.syn.synold4s.vm.SurveillanceViewModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class SurveillanceActivity extends BaseActivity<ActivitySurveillanceBinding, SurveillanceViewModel> implements View.OnClickListener, IView, TextWatcher {

    private CctvRvAdapter adapter;
    protected LinearLayoutManager mLinearLayoutManager;
    private int pageIndex = 1;
    private DrawerAdapter mDrawerAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_surveillance;
    }

    @Override
    protected void initView() {
        WindowUtil.setWindowDecorView(this);
        //设置禁止上拉加载
        mBinding.smartRefreshLayout.setEnableLoadMore(false);
//        mBinding.smartRefreshLayout.setTag(Constants.REFRESH);
        initListener();
        initAdapter();
        getCctv();
        initDrawer();
    }

    private void initDrawer() {
        mBinding.tvVersion.setText("V" + AppUtil.getVersion());
        mBinding.tvSetting.setOnClickListener(view -> {
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
            startActivity(new Intent(this, SettingActivity.class));
        });
        mBinding.cctvToolbar.setOnBackListener(() -> mBinding.drawerLayout.openDrawer(GravityCompat.START));
        mBinding.tvDeviceStatus.setOnClickListener(view -> {
            boolean status = !mBinding.tvDeviceStatus.isSelected();
            mBinding.tvDeviceStatus.setSelected(status);
            MyAnimUtil.startAnim(mBinding.rvDeviceStatus, !status);
        });
        mBinding.tvLocation.setOnClickListener(view -> {
            startActivity(new Intent(this, GoogleMapActivity.class));
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
        });
        mBinding.tvSurveillance.setOnClickListener(view -> mBinding.drawerLayout.closeDrawer(GravityCompat.START));
        mDrawerAdapter = new DrawerAdapter(this);
        mDrawerAdapter.setOnItemClickListener((v, position) -> {
            startActivity(new Intent(this, MainActivity.class));
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
        });
        mBinding.rvDeviceStatus.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvDeviceStatus.setAdapter(mDrawerAdapter);
        mBinding.rvDeviceStatus.setVisibility(View.GONE);
    }

    private void initListener() {
        mBinding.btnPrevPage.setOnClickListener(this);
        mBinding.btnNextPage.setOnClickListener(this);
        mBinding.cctvToolbar.setOnBackListener(this::finish);
        //返回键处理
        getOnBackPressedDispatcher().addCallback(mContext, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                if (CustomManager.backFromWindowFull(mContext, adapter.getFullKey())) {//全屏状态
                    return;
                }
                finish();
            }
        });
        mBinding.ivSearch.setOnClickListener(view -> getCctv());
        mBinding.etSearchCctv.setOnEditorActionListener((v, actionId, event) -> searchEditorAction(actionId));
        mBinding.etSearchCctv.addTextChangedListener(this);

        mBinding.smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            mBinding.smartRefreshLayout.setTag(Constants.REFRESH);
            getCctv();
        });
    }

    private boolean searchEditorAction(int actionId) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            WindowUtil.hideSoftInput(mBinding.etSearchCctv);
            getCctv();
            return true;
        }
        return false;
    }

    private void initAdapter() {
        adapter = new CctvRvAdapter(mContext);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mBinding.rvCctv.setLayoutManager(mLinearLayoutManager);
        mBinding.rvCctv.setAdapter(adapter);
        mBinding.rvCctv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
                int visibleItemCount = recyclerView.getChildCount();
                int lastVisibleItem = firstVisibleItem + visibleItemCount;
                //item不可见时  暂停播放并且释放资源
                //大于0说明有播放
//                if (CustomManager.instance().size() >= 0) {
//                    Map<String, CustomManager> map = CustomManager.instance();
//                    List<String> removeKey = new ArrayList<>();
//                    for (Map.Entry<String, CustomManager> customManagerEntry : map.entrySet()) {
//                        CustomManager customManager = customManagerEntry.getValue();
//                        //当前播放的位置
//                        int position = customManager.getPlayPosition();
//                        //对应的播放列表TAG
//                        if (customManager.getPlayTag().equals(adapter.TAG)
//                                && (position < firstVisibleItem || position > lastVisibleItem)) {
//                            CustomManager.releaseAllVideos(customManagerEntry.getKey());
//                            removeKey.add(customManagerEntry.getKey());
//                        }
//                    }
//                    if (removeKey.size() > 0) {
//                        for (String key : removeKey) {
//                            map.remove(key);
//                        }
//                        adapter.notifyDataSetChanged();
//                    }
//                }
            }
        });
    }

    @Override
    protected void initData() {
        String tagListStr = SPUtil.getInstance().getString(SPName.TAG, "");
        if (!tagListStr.isEmpty()) {
            List<UserTagDto> userTagDtos = (List<UserTagDto>) GsonUtil.getInstance().fromJson(tagListStr, new TypeToken<List<UserTagDto>>() {
            }.getType());
            if (userTagDtos != null) {
                mViewModel.getUserTag().setValue(userTagDtos);
            }
        }
        mViewModel.getTag();
    }

    @Override
    protected void initLiveData() {
        mViewModel.getCctvResult().observe(mContext, cctvDtos -> {
            if (cctvDtos != null && cctvDtos.size() == 1) {
                adapter.setSize(cctvDtos.size());
            }
            adapter.submitList(cctvDtos);
        });

        mViewModel.getResultCode().observe(mContext, resultCode -> {
            SmartRefreshUtil.refreshSmartRefreshLayout(mBinding.smartRefreshLayout);
        });
        // 獲取項目對應的子模塊
        mViewModel.getTagByProj().observe(this, this::handleTag);
        // 根据tag显示对应板块
        mViewModel.getUserTag().observe(this, this::handleUserTag);
    }

    /**
     * 处理主页显示的版块
     */
    private void handleUserTag(List<UserTagDto> data) {
        List<UserTagDto> drawerList = new ArrayList<>();
        drawerList.add(new UserTagDto("all", getString(R.string.all_big)));
        for (UserTagDto userTagDto : data) {
            if (Objects.equals(userTagDto.getCode(), "SynAlert") || (Objects.equals(userTagDto.getOwPage(), "All")
                    && !Objects.equals(userTagDto.getCode(), TagCode.codeSurveillance)
                    && !Objects.equals(userTagDto.getCode(), "SynDSM"))) {
//                && !Objects.equals(userTagDto.getCode(), "SynTowerCrane")
                drawerList.add(userTagDto);
            }
        }
        mDrawerAdapter.submitList(drawerList);
    }


    /**
     * 处理對應的子模塊
     */
    private void handleTag(LoginDto data) {
        List<UserTagDto> synProjs = data.getTags();
        if (synProjs != null) {
            // 需要显示的版块
            List<UserTagDto> tags = new ArrayList<>();
            StringBuilder codesStr = new StringBuilder();
            for (UserTagDto userTag : synProjs) {
                if (TextUtils.isEmpty(userTag.getCode())) {
                    continue;
                }
                if (userTag.getCode().equals(TagCode.codeSurveillance)) {
                    tags.add(userTag);
                } else {
                    if (Objects.equals(userTag.getOwPage(), "All")
                            || Objects.equals(userTag.getOwPage(), "Dashboard")
                            || !Objects.equals(userTag.getOwPage(), TagCode.codeDriver)) {
                        codesStr.append(",").append(userTag.getCode());
                        tags.add(userTag);
                    }
                }
            }
            mViewModel.getUserTag().setValue(tags);
            SPUtil.getInstance().putString(SPName.TAG_CODE, codesStr.length() > 0 ? codesStr.substring(1) : "");
            SPUtil.getInstance().putString(SPName.TAG, GsonUtil.getInstance().toJson(tags));
        }
    }

    @Override
    protected int initVariable() {
        return 0;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_next_page) {
            next();
        } else if (id == R.id.btn_prev_page) {
            prev();
        }
    }

    private void prev() {
        if (pageIndex == 1) return;
        pageIndex--;
        getCctv();
    }

    private void next() {
        pageIndex++;
        getCctv();
    }

    private void getCctv() {
        mBinding.btnPrevPage.setImageResource(pageIndex == 1 ? R.drawable.icon_before_disable : R.drawable.icon_before);
        mBinding.btnPrevPage.setEnabled(pageIndex != 1);
        mBinding.tvPage.setText(getString(R.string.page_number, pageIndex));
        adapter.clear();
        mViewModel.getCctv(pageIndex, mBinding.etSearchCctv.getText().toString().trim());
    }

    @Override
    protected void event(Event event) {

    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {

    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {

    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    @Override
    protected void onPause() {
        super.onPause();
        CustomManager.onPauseAll();
    }

    @Override
    protected void onResume() {
        super.onResume();
        CustomManager.onResumeAll();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CustomManager.clearAllVideo();
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (TextUtils.isEmpty(mBinding.etSearchCctv.getText().toString().trim())) {
            getCctv();
        }
    }
}